package com.remote.common.context.serialization;


import com.remote.common.model.Request;
import com.remote.common.model.Response;
import com.remote.common.util.SerializationUtil;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

/**
 * User:cool coding
 * Date:2018/1/7
 * Time:21:27
 * 解码
 */
public class ProtobufDecoder extends ByteToMessageDecoder {
    private Class<?> genericClass;

    public ProtobufDecoder(Class<?> genericClass) {
        this.genericClass = genericClass;
    }

    private static final Logger LOGGER = LoggerFactory.getLogger(ProtobufDecoder.class);

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) {
        try {
            if (in.readableBytes() < 4) {
                return;
            }
            in.markReaderIndex();
            int dataLength = in.readInt();
            if (dataLength < 0) {
                ctx.close();
            }
            if (in.readableBytes() < dataLength) {
                in.resetReaderIndex();
                return;
            }
            byte[] data = new byte[dataLength];
            in.readBytes(data);
            Object obj = SerializationUtil.deserialize(data, genericClass);
            out.add(obj);
        } catch (Exception e) {
            if (genericClass == Request.class) {
                LOGGER.debug("解译服务端数据异常", e);
            } else if (genericClass == Response.class) {
                LOGGER.debug("解译客户端端数据异常", e);
            } else {
                LOGGER.debug("解译数据异常", e);
            }
        }
    }

    @Override
    public boolean isSharable() {
        return super.isSharable();
    }
}
